package com.dwjm.client;

import com.dwjm.ConnectionDatabaseForMySQLUserJdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/Clogin")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置编码和响应类型
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String account = request.getParameter("account");
        String password = request.getParameter("password1");

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = ConnectionDatabaseForMySQLUserJdbc.getConnection();
            String sql = "SELECT * FROM t_consumer WHERE account = ? AND password1 = ? AND state = 0";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, account);
            stmt.setString(2, password);
            rs = stmt.executeQuery();

            if (rs.next()) {
                // 登录成功
                String username = rs.getString("realname"); // 可用于前端显示
                response.getWriter().write("{\"code\":200,\"msg\":\"登录成功\",\"username\":\"" + username + "\"}");
            } else {
                // 登录失败
                response.getWriter().write("{\"code\":400,\"msg\":\"账号或密码错误，或账号已被禁用\"}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"code\":500,\"msg\":\"服务器异常\"}");
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception ignored) {}
            try { if (stmt != null) stmt.close(); } catch (Exception ignored) {}
            try { if (conn != null) conn.close(); } catch (Exception ignored) {}
        }
    }
}